package com.mogist.hqc.module.personal.ui

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.view.View
import android.widget.AdapterView
import butterknife.OnClick
import butterknife.Optional
import com.mogist.hqc.R
import com.mogist.hqc.base.BaseMVPActivity
import com.mogist.hqc.entitys.BaseModel
import com.mogist.hqc.entitys.response.LoginVo
import com.mogist.hqc.module.personal.contract.InfoContract
import com.mogist.hqc.module.personal.presenter.InfoPresenter
import com.mogist.hqc.mvp.HttpDto
import com.mogist.hqc.oss.OssManager
import com.mogist.hqc.util.Constant
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_info.*
import kotlinx.android.synthetic.main.include_title.*
import org.greenrobot.eventbus.Subscribe
import talex.zsw.basecore.interfaces.OnSimpleListener
import talex.zsw.basecore.util.*
import talex.zsw.basecore.util.glide.GlideApp
import talex.zsw.basecore.view.dialog.rxdialog.RxDialogChooseImage
import talex.zsw.basecore.view.dialog.rxdialog.RxDialogEditSureCancel
import talex.zsw.basecore.view.dialog.sweetalertdialog.SweetAlertDialog
import talex.zsw.basecore.view.other.RxToast
import talex.zsw.basecore.view.other.slidedatetimepicker.SlideDateTimeListener
import talex.zsw.basecore.view.other.slidedatetimepicker.SlideDateTimePicker
import java.util.*

/**
 * 作用：个人资料
 * 作者：赵小白 email:vvtale@gmail.com  
 * 修改人：
 * 修改时间：
 * 修改备注：
 */
class InfoActivity : BaseMVPActivity<InfoContract.Presenter>(), InfoContract.View
{
    override fun initArgs(intent: Intent?)
    {
    }

    override fun initView()
    {
        setContentView(R.layout.activity_info)
        mPresenter = InfoPresenter(this)
    }

    override fun initData()
    {
        mTitleBar.setTitle("个人资料")
        val loginVo = SpTool.getObject(Constant.OBJ_LOGIN, LoginVo::class.java)
        headImg = DataTool.getNotNull(loginVo.headImg)
        if (RegTool.isNotEmpty(headImg))
        {
            GlideApp.with(mIvPhoto.context)
                    .load(headImg)
                    .centerCrop()
                    .into(mIvPhoto)
        }
        nickname = DataTool.getNotNull(loginVo.nickName)
        mTvName.text = nickname
        birthDay = DataTool.getNotNull(loginVo.birthStringDay)
        mTvBirthday.text = birthDay
        sex = DataTool.getNotNull(loginVo.sex)
        var pos = 0 // 0或空:未设置 1:男性  2:女性
        if ("1" == sex)
        {
            pos = 1
        }
        else if ("2" == sex)
        {
            pos = 2
        }
        initSpinner(pos)
    }

    override fun onResume()
    {
        super.onResume()
        if (RegTool.isEmpty(SpTool.getString(Constant.STR_MOBILE)))
        {
            mTvPhone.text = "立即绑定手机"
        }
        else
        {
            mTvPhone.text = SpTool.getString(Constant.STR_MOBILE)
        }
    }

    @Optional
    @OnClick(R.id.mLLPhoto, R.id.mLLName, R.id.mLLSex, R.id.mLLBirthday, R.id.mLLPhone)
    fun onViewClicked(view: View)
    {
        if (!isFastClick)
        {
            when (view.id)
            {
                R.id.mLLPhoto    ->
                { // 头像
                    PermissionHelper.check(OnSimpleListener {
                        showRxChooseImg()
                    }, PermissionConstants.CAMERA, PermissionConstants.STORAGE)
                }
                R.id.mLLName     ->
                { // 昵称
                    showRxEditDialog()
                }
                R.id.mLLSex      ->
                { // 性别
                }
                R.id.mLLBirthday ->
                { // 生日
                    showDataTimePicker()
                }
                R.id.mLLPhone    ->
                { // 电话
                    if (RegTool.isEmpty(SpTool.getString(Constant.STR_MOBILE)))
                    {
                        start(BindMobileActivity::class.java)
                    }
                }
            }
        }
    }

    override fun onBackPressed()
    {
        if (rxChooseImg != null && rxChooseImg!!.isShowing)
        {
            rxChooseImg?.dismiss()
        }
        else
        {
            super.onBackPressed()
        }
    }

    // --------------- 选择图片 ---------------
    private var rxChooseImg: RxDialogChooseImage? = null

    private fun showRxChooseImg()
    {
        rxChooseImg
                ?: let {
                    rxChooseImg = RxDialogChooseImage(this@InfoActivity)
                }
        rxChooseImg?.showWithPermission()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)
    {
        when (requestCode)
        {
            PhotoTool.GET_IMAGE_FROM_PHONE ->
            { //选择相册之后的处理
                if (resultCode == RESULT_OK)
                {
                    PhotoTool.cropImage(this@InfoActivity, data?.data, 1, 1, 250, 250) // 裁剪图片
                }
            }
            PhotoTool.GET_IMAGE_BY_CAMERA  ->
            { //选择相册之后的处理
                if (resultCode == RESULT_OK)
                {
                    PhotoTool.cropImage(this@InfoActivity,
                                        PhotoTool.imageUriFromCamera,
                                        1,
                                        1,
                                        250,
                                        250) // 裁剪图片
                }
            }
            PhotoTool.CROP_IMAGE           ->
            { // 裁剪完成以后
                userHead = PhotoTool.cropImageUri
                headImg = ""
                mIvPhoto.setImageURI(PhotoTool.cropImageUri)
                setChange()
            }
        }
        super.onActivityResult(requestCode, resultCode, data)
    }

    // ------------------ NiceSpinner ------------------
    private val datas: ArrayList<String> = arrayListOf()

    private fun initSpinner(pos: Int)
    {
        datas.add("请选择")
        datas.add("男")
        datas.add("女")
        mNiceSpinner.attachDataSource(datas)
        mNiceSpinner.selectedIndex = pos
        mNiceSpinner.setOnItemSelectedListener(object : AdapterView.OnItemSelectedListener
                                               {
                                                   override fun onNothingSelected(parent: AdapterView<*>?)
                                                   {
                                                   }

                                                   override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long)
                                                   {
                                                       sex = position.toString()
                                                       setChange()
                                                   }
                                               })
    }

    // --------------- 昵称 ---------------
    var rxEditDialog: RxDialogEditSureCancel? = null

    private fun showRxEditDialog()
    {
        rxEditDialog
                ?: let {
                    rxEditDialog = RxDialogEditSureCancel(it)
                    rxEditDialog?.setTitle("修改昵称")
                    rxEditDialog?.setSureListener {
                        nickname = rxEditDialog?.editText?.text.toString()
                        mTvName.text = nickname
                        setChange()
                        rxEditDialog?.dismiss()
                    }
                }
        rxEditDialog?.show()
    }

    // --------------- 生日 ---------------
    var timePicker: SlideDateTimePicker? = null
    var birthday = Date()
    private fun showDataTimePicker()
    {
        timePicker
                ?: let {
                    timePicker =
                            SlideDateTimePicker.Builder(supportFragmentManager)
                                    .setListener(object : SlideDateTimeListener()
                                                 {
                                                     override fun onDateTimeSet(date: Date)
                                                     {
                                                         birthDay =
                                                                 TimeTool.date2String(date,
                                                                                      TimeTool.STR_FOMATER_DATA)
                                                         mTvBirthday.text = birthDay
                                                         setChange()
                                                     }
                                                 })
                                    .setInitialDate(birthday)
                                    .setMaxDate(Date())
                                    .setThemeColor(ColorTool.getColorById(R.color.colorPrimary))
                                    .setTitleColor(ColorTool.getColorById(R.color.white))
                                    .setShowTime(false)
                                    .setShowDay(true)
                                    .build()
                }
        timePicker?.show()
    }

    // --------------- 修改用户信息 ---------------
    private var userHead: Uri? = null
    private var isChange = false
    private var nickname = ""
    private var birthDay = ""
    private var headImg = ""
    private var sex = "" // 0或空:未设置 1:男性  2:女性

    private fun setChange()
    {
        isChange = true
        mTitleBar.setRightTV("保存") { upload() }
    }

    private fun upload()
    {
        if (userHead != null && RegTool.isEmpty(headImg))
        {
            uploadImg()
        }
        else
        {
            val body = BaseModel(true)
            body.headImg = headImg
            body.nickName = nickname
            body.birthStringDay = birthDay
            body.sex = sex
            mPresenter.getData(HttpDto(Constant.PERSONAL_INFO_UPDATE,
                                       body).setErrorTitle("修改用户信息失败"))
        }
    }

    override fun uploadSuccess()
    {
        disDialog()
        RxToast.success("修改成功")
        val loginVo = SpTool.getObject(Constant.OBJ_LOGIN, LoginVo::class.java)
        loginVo.headImg = headImg
        loginVo.nickName = nickname
        loginVo.birthStringDay = birthDay
        loginVo.sex = sex
        SpTool.saveString(Constant.STR_USER_PHOTO, headImg)
        SpTool.saveString(Constant.STR_USER_NAME, nickname)
        SpTool.saveObject(Constant.OBJ_LOGIN, loginVo)
        finish()
    }

    @SuppressLint("CheckResult")
    private fun uploadImg()
    {
        showDialog()
        Observable.just(userHead!!)
                .subscribeOn(Schedulers.io())
                .map { v ->
                    BitmapTool.getBitmap(v, this@InfoActivity)
                }
                .subscribe { bitmap ->
                    OssManager.getInstance()
                            .upload(1, bitmap, object : OssManager.OnUploadListener
                            {
                                override fun onProgress(position: Int, currentSize: Long, totalSize: Long)
                                {
                                    LogTool.ni("position = $position  进度 = $currentSize /$totalSize")
                                }

                                override fun onSuccess(position: Int, imageUrl: String?)
                                {
                                    runOnUiThread {
                                        headImg = imageUrl.toString()
                                        upload()
                                    }
                                }

                                override fun onFailure(position: Int)
                                {
                                    LogTool.ni("失败的position = " + position)
                                    runOnUiThread {
                                        headImg = ""
                                        showDialog(SweetAlertDialog.ERROR_TYPE,
                                                   "上传头像失败",
                                                   "请检查网络后重试")
                                    }
                                }
                            })
                }
    }

    // --------------- EventBus ---------------
    @Subscribe
    fun onEvent(event: String)
    {
        if (event == Constant.EVENT_PAY_FAILED)
        {
            finish()
        }
    }

}